package com.kapcb.log;

import com.kapcb.log.filter.RequestLoggingFilter;
import com.kapcb.log.filter.TraceFilter;
import com.kapcb.log.properties.LogProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;

/**
 * <a>Title: LogAutoConfiguration </a>
 * <a>Author: kapcb <a>
 * <a>Description: LogAutoConfiguration <a>
 *
 * @author Kpacb
 * @version 1.0
 * @date 2024/5/25 11:11
 * @since 1.0
 */
@Slf4j
@Order(Ordered.HIGHEST_PRECEDENCE)
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(LogProperties.class)
public class LogAutoConfiguration {

    private LogProperties logProperties;

    @Autowired
    public void setLogProperties(LogProperties logProperties) {
        this.logProperties = logProperties;
    }

    @Bean("traceFilter")
    @ConditionalOnMissingBean(name = "traceFilter")
    public FilterRegistrationBean<TraceFilter> traceFilter() {
        if (log.isDebugEnabled()) {
            log.debug("begin load traceFilter into IOC ...");
        }
        FilterRegistrationBean<TraceFilter> filterRegistrationBean = new FilterRegistrationBean<>();
        filterRegistrationBean.setFilter(new TraceFilter());
        filterRegistrationBean.setOrder(-100000);
        return filterRegistrationBean;
    }

    @Bean(name = "requestLoggingFilter")
    @ConditionalOnMissingBean(name = "requestLoggingFilter")
    public FilterRegistrationBean<RequestLoggingFilter> requestLoggingFilter() {
        if (log.isDebugEnabled()) {
            log.debug("begin load requestLoggingFilter into IOC ...");
        }
        FilterRegistrationBean<RequestLoggingFilter> filterRegistrationBean = new FilterRegistrationBean<>();
        filterRegistrationBean.setFilter(new RequestLoggingFilter(logProperties));
        filterRegistrationBean.setName("requestLoggingFilter");
        filterRegistrationBean.setOrder(0);
        return filterRegistrationBean;
    }

}
